<template>
  <div class="app-container">
    <el-form :model="queryParams1" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品批次" prop="productBatch">
        <el-input  v-model="queryParams1.productBatch" placeholder="请输入产品批次"
                   clearable   readonly>
          <el-button slot="append"    @click="handleShowCheckItemOpen">选择</el-button>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="small" @click="handleQuery" style="top: 10px">查询</el-button>
      </el-form-item>
    </el-form>

<!--    {{d}}-->
    <div id="showCarbonChart" style="width: 100%;height: 730px">



    </div>

    <el-dialog title="选择产品批次" :visible.sync="checkItemOpen" width="700px" append-to-body custom-class="dialogPadDiv" >
      <el-form :model="queryParams" ref="queryBatchParamsForm" :inline="true" label-width="68px">
        <el-form-item label="产品分类" >
          <el-cascader style="width: 100%"  size="small"
                       v-model="categorizeArr" @change="changeProductCategorize"
                       :options="$store.state.factorDict.productCategorizeDict0"
                       :props="{value:'code',label:'chineseName' ,checkStrictly: true }"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-select v-model="queryParams.productId" placeholder="请选择产品" clearable size="small">
            <el-option v-for="dict in productInfoOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="所属企业" prop="enterpriseId">
          <el-cascader  v-model="enterpriseIdArr" style="width: 100%"
                        :options="$store.state.factorDict.enterpriseDict" :show-all-levels="false"
                        :props="{value:'id',label:'enterpriseName',children:'children',checkStrictly:true,}"
                        clearable></el-cascader>
        </el-form-item>
        <el-form-item label="产品批次" prop="productBatch">
          <el-input  v-model="queryParams.productBatch" placeholder="请输入产品批次" clearable   />
        </el-form-item>
        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleBatchQuery">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table border   :data="productCarbonList" height="400px"  highlight-current-row
                @current-change="handleCurrentChange">
        <el-table-column label="序号" align="center" type="index" width="50" />
        <!--        <el-table-column label="分类" align="center" >-->
        <!--          <template slot-scope="scope">-->
        <!--            {{selectDictLabel($store.state.factorDict.productCategorizeDict0, scope.row.level0,'code','chineseName')}}-->
        <!--            {{scope.row.level1?' / ':''}}-->
        <!--            {{selectDictLabel($store.state.factorDict.productCategorizeDict1, scope.row.level1,'code','chineseName')}}-->
        <!--            {{scope.row.level2?' / ':''}}-->
        <!--            {{selectDictLabel($store.state.factorDict.productCategorizeDict2, scope.row.level2,'code','chineseName')}}-->
        <!--            {{scope.row.level3?' / ':''}}-->
        <!--            {{selectDictLabel($store.state.factorDict.productCategorizeDict3, scope.row.level3,'code','chineseName')}}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="所属企业" align="center" prop="enterpriseId" >
          <template slot-scope="scope">
            {{selectDictLabel($store.state.factorDict.enterpriseOptions, scope.row.enterpriseId,'id','enterpriseName')}}
          </template>
        </el-table-column>
        <el-table-column label="产品批次" align="center" prop="productBatch"/>
      </el-table>
      <pagination style="margin-top: 0"  v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"  @pagination="handleBatchQuery" />
      <div slot="footer" class="dialog-footer" >
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  // import 'echarts-liquidfill'
  import { listProductCarbon, getInfoAndConsumables, delProductCarbon, addProductCarbon, updateProductCarbon, downloadProductCarbon } from "@/api/carbon/productCarbon";
  import { listProductInfo } from "@/api/factor/productInfo";
export default {
  name: "ProductCarbonConChart",
  components:{
  },
  data() {
    return {  // 显示搜索条件
      showSearch: true,
      // // 查询参数
      queryParams1: {
        productId: null,
        productName: null,
        id: null,
      },
      //产品库
      productInfoOptions:[],
      enterpriseIdArr:[],
      categorizeArr:[],
      checkItemOpen: false,
      productCarbonList:[],
      queryParams:{
        productBatch:null,
        level0: null,
        level1: null,
        level2: null,
        productId: null,
        level3: null,
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      currentRow:null,
      chart:null,
    };
  },
  created() {

  },
  methods: {
    handleQuery(){
      if(!this.queryParams1.id){
        this.msgError("请选择产品批次");
        return;
      }
      getInfoAndConsumables(this.queryParams1.id).then(res=>{
        let data =[];
        let links =[];
        let nameMap={};
        let stageList = res.data['stageList'];
        for (let item of stageList){
          nameMap["S_"+item.id] = item.name;
        }
        for(let item of res.data['consumables']){
          let stage = stageList.filter(v=>v.id==item.stageId);
          let categorizeCode = item.categorizeCode;
          let arr = categorizeCode.split(",");
          let val = item.factorNum&&item.quantity?(item.factorNum*item.quantity):0;
          if(!nameMap["A_"+arr[2]]){
            nameMap["A_"+arr[2]] = this.selectDictLabel(this.$store.state.factorDict.categorizeInfoOptions, arr[2],'id','chineseName')+'(Ⅲ)'
          }
          if(!nameMap["A_"+arr[1]]){
            nameMap["A_"+arr[1]] = this.selectDictLabel(this.$store.state.factorDict.categorizeInfoOptions, arr[1],'id','chineseName')+"(Ⅱ)"
          }
          if(!nameMap["A_"+arr[0]]){
            nameMap["A_"+arr[0]] = this.selectDictLabel(this.$store.state.factorDict.categorizeInfoOptions, arr[0],'id','chineseName')+'(Ⅰ)'
          }
          data.push(nameMap["S_"+stage[0].parentId]);
          data.push(nameMap["S_"+item.stageId]);
          data.push(nameMap["A_"+arr[2]]);
          data.push(nameMap["A_"+arr[1]]);
          data.push(nameMap["A_"+arr[0]]);
          data.push(item.name);
          links.push({ source: nameMap["S_"+stage[0].parentId],target:nameMap["S_"+item.stageId], value: val });
          links.push({ source: nameMap["S_"+item.stageId],target: item.name, value: val });
          links.push({ source: item.name,target: nameMap["A_"+arr[2]], value: val });
          links.push({ source: nameMap["A_"+arr[2]],target: nameMap["A_"+arr[1]], value: val });
          links.push({ source: nameMap["A_"+arr[1]],target: nameMap["A_"+arr[0]], value: val });
        }
        this.showChart(
          data.reduce((acc, cur) => {  if (!acc.includes(cur)) {  acc.push(cur); } return acc; }, [])
            .map(item => {return { name: item, }; })
            ,links)
      })
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    changeProductCategorize(){
      let params={};
      if(this.categorizeArr.length>0){
        params.level0 = this.categorizeArr[0]
      }
      if(this.categorizeArr.length>1){
        params.level1 = this.categorizeArr[1]
      }
      if(this.categorizeArr.length>2){
        params.level2 = this.categorizeArr[2]
      }
      if(this.categorizeArr.length>3){
        params.level3 = this.categorizeArr[3]
      }
      listProductInfo(params).then(response => {
        this.productInfoOptions = response.rows;
      });
    },
    cancel(){
      this.enterpriseIdArr=[];
      this.queryParams.productBatch=null;
      this.productCarbonList = [];
      this.total = 0;
      this.checkItemOpen=false
    },
    handleShowCheckItemOpen(){
      this.enterpriseIdArr=[];
      this.queryParams.productBatch=null;
      this.productCarbonList = [];
      this.total = 0;
      this.checkItemOpen=true;
      this.handleBatchQuery();
    },
    handleBatchQuery(){
      if(this.enterpriseIdArr.length>0){
        this.queryParams.enterpriseId = this.enterpriseIdArr[this.enterpriseIdArr.length-1];
      }else {
        this.queryParams.enterpriseId = null;
      }
      listProductCarbon(this.queryParams).then(response => {
        this.productCarbonList = response.rows;
        this.total = response.total;
      });
    },
    submitForm(){
      if(this.currentRow==null){
        return
      }
      this.queryParams1.productId = this.currentRow.productId;
      this.queryParams1.productBatch = this.currentRow.productBatch;
      this.queryParams1.id = this.currentRow.id;
      this.checkItemOpen=false
    },
    getDefaultOp(){
      return {
        tooltip: {
          trigger: 'item',
          triggerOn: 'mousemove',
          formatter: (params) => {
            let { source, target, value } = params.data;
            if(source&&target&&value){
              return `${source} -> ${target} : ${value}`
            }
           return params.name;
          }
        },
        series: {
          type: 'sankey',
          layout: 'none',
          emphasis: {
            focus: 'adjacency'
          },
          data: [],
          links: [],
        }
      }
    },
    showChart(data,links){
      let _chart;
      if(this['chart']){
        _chart = this['chart'];
      }else {
        let chart = document.getElementById('showCarbonChart');
        if(chart==null){
          return
        }

        _chart = this.$echarts.init(chart);
      }
      let option = this.getDefaultOp();
      option.series.data=data;
      option.series.links=links;
      _chart.setOption(option);
      this['chart'] = _chart;
    },



  }
};
</script>
